Skip to main content

MERN SHOW

Let's add a function that will select a holiday when a mouse hovers over one in our list

First, let's add a property to state

const [holidays, setHolidays] = useState([]);const [holiday, setHoliday] = useState(null);

Let's call setHoliday on mouseover. Again because we want to pass an argument, we must wrap this in an anonymous function

<tr key={index} onMouseOver={() => setHoliday(holiday)}></tr>

Let's show our Show component if holiday has a non false-y value, right after our table

<Show holiday={holiday} />

Create and import the Show component

const Show = ({ holiday }) => {  if (holiday === null) {    return null;    }
  const celebrated = holiday.celebrated ? "Yes" : "No";
  return (    <div>      <h2>{holiday.name}</h2>      <h3>Celebrated: {celebrated}</h3>      <p>{holiday.description}</p>      <p>Likes: {holiday.likes}</p>      <ul>        {holiday.tags.map((tag) => (          <li>{tag}</li>        ))}      </ul>    </div>  );};
export default Show;

Import into App.js

import Show from "./components/Show.js";

COMPLETED CODE:

App.js#

import "bulma/css/bulma.css";import { useEffect, useState } from "react";import NewForm from "./components/NewForm";import Show from "./components/Show";
const App = () => {  const [holidays, setHolidays] = useState([]);  const [holiday, setHoliday] = useState(null);
  const addHoliday = (holiday) => {    setHolidays([...holidays, holiday]);  };
  const deleteHoliday = (id) => {    fetch("/holidays/" + id, {      method: "DELETE",    }).then((response) => {      setHolidays(holidays.filter((day) => day._id !== id));    });  };
  useEffect(() => {    fetch("/holidays")      .then(        (data) => data.json(),        (err) => console.log(err)      )      .then(        (parsedData) => setHolidays(parsedData),        (err) => console.log(err)      );  }, []);
  return (    <div className="container">      <h1 className="title">Holidays! Celebrate!</h1>      <NewForm handleAddHoliday={addHoliday} />      <Show holiday={holiday} />      <table>        <tbody>          {holidays.map((holiday) => {            return (              <tr key={holiday._id} onMouseOver={() => setHoliday(holiday)}>                <td> {holiday.name}</td>                <td onClick={() => deleteHoliday(holiday._id)}>X</td>              </tr>            );          })}        </tbody>      </table>    </div>  );};
export default App;